#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# @Time    : 2025/9/30 16:39
# @Author  : WXY
# @File    : ProjectHelp
# @PROJECT_NAME: youtubedown_gui
# @PRODUCT_NAME: PyCharm
# -------------------------------------------------------------------------------

import sys
import os
import base64
from PySide6.QtWidgets import QMainWindow, QApplication
from PySide6.QtCore import Qt
from py_gui.projecthelp_ui import Ui_projecthelp
from utils import setup_window_icon, setup_window_title, get_resource_path
from LoggerManager import logger_manager
from i18n import i18n_manager, _

try:
    from py_gui import resouce_rc  # 导入资源文件
    print("✅ 项目帮助资源文件导入成功")
except ImportError as e:
    print(f"⚠️ 项目帮助资源文件导入失败: {e}")


class ProjectHelpWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_projecthelp()
        self.ui.setupUi(self)
        
        # 设置窗口属性
        self.setup_window()
        
        # 设置内容
        self.setup_content()
        
        # 连接信号
        self.setup_connections()
        # 设置为只读
        self.ui.txt_content.setReadOnly(True)

        # 关键：启用外部链接点击功能
        self.ui.txt_content.setOpenExternalLinks(True)
        logger_manager.info("项目帮助窗口初始化完成", "ProjectHelp")

    def setup_window(self):
        """设置窗口属性"""
        try:
            # 设置窗口标题
            self.setWindowTitle(_("windows.project_help_title", "项目帮助"))
            
            # 设置窗口图标
            setup_window_icon(self)
            
            # 设置窗口大小
            self.resize(800, 600)
            self.setMinimumSize(600, 400)
            
            logger_manager.info("项目帮助窗口属性设置完成", "ProjectHelp")
            
        except Exception as e:
            logger_manager.error(f"设置项目帮助窗口属性失败: {e}", "ProjectHelp")

    def get_image_base64(self, image_path):
        """将图片转换为base64格式，兼容打包环境"""
        try:
            # 获取正确的图片路径
            if getattr(sys, 'frozen', False):
                # 打包环境：从 _MEIPASS 获取
                full_path = os.path.join(sys._MEIPASS, 'imgs', image_path)
            else:
                # 开发环境：相对于当前文件的路径
                current_dir = os.path.dirname(os.path.abspath(__file__))
                full_path = os.path.join(os.path.dirname(current_dir), 'imgs', image_path)
            
            if os.path.exists(full_path):
                with open(full_path, "rb") as img_file:
                    img_data = img_file.read()
                    img_base64 = base64.b64encode(img_data).decode('utf-8')
                    return f"data:image/jpeg;base64,{img_base64}"
            else:
                logger_manager.warning(f"图片文件不存在: {full_path}", "ProjectHelp")
                return ""
        except Exception as e:
            logger_manager.error(f"转换图片为base64失败: {e}", "ProjectHelp")
            return ""

    def setup_content(self):
        """设置帮助内容"""
        try:
            # 获取咖啡图片的base64编码
            coffee_image_base64 = self.get_image_base64("custom_coffee.jpg")
            
            # HTML 内容
            html_content = f"""
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <style>
                    body {{
                        font-family: 'Microsoft YaHei', Arial, sans-serif;
                        background: transparent;
                        color: #ffffff;
                        margin: 10px;
                        line-height: 1.6;
                    }}
                    h1 {{
                        color: #00d4ff;
                        border-bottom: 2px solid #00d4ff;
                        padding-bottom: 5px;
                        margin-bottom: 15px;
                    }}
                    h2 {{
                        color: #0099cc;
                        margin-top: 20px;
                        margin-bottom: 10px;
                    }}
                    p {{
                        margin-bottom: 10px;
                        text-indent: 2em;
                    }}
                    ul {{
                        margin-left: 20px;
                    }}
                    li {{
                        margin-bottom: 5px;
                    }}
                    a {{
                        color: #00d4ff;
                        text-decoration: none;
                    }}
                    a:hover {{
                        color: #0066ff;
                        text-decoration: underline;
                    }}
                    .highlight {{
                        background-color: rgba(0, 212, 255, 0.2);
                        padding: 2px 4px;
                        border-radius: 3px;
                    }}
                    .code {{
                        background-color: rgba(255, 255, 255, 0.1);
                        padding: 2px 6px;
                        border-radius: 3px;
                        font-family: 'Consolas', 'Monaco', monospace;
                        font-size: 0.9em;
                    }}
                </style>
            </head>
            <body>
                <h2>📖 1. {_("help.project_description", "项目说明")}</h2>
                <p>{_("help.project_intro", "本项目是一个基于 yt_dlp 封装的桌面应用程序，用来下载YouTube的视频到本地设备上，需要科学工具。")}</p>
                
                <h2>📋 2. {_("help.usage_instructions", "使用说明")}</h2>
                <ul>
                    <li>{_("help.step1", "在URL输入框中粘贴YouTube视频或播放列表链接")}</li>
                    <li>{_("help.step2", "选择下载文件保存路径")}</li>
                    <li>{_("help.step3", "设置分辨率限制（可选）, 默认不限制, 表示下载最好的分辨率")}</li>
                    <li>{_("help.step4", "选择是否只下载MP4格式")}</li>
                    <li>{_("help.step5", "设置YouTube的Cookies, 请点击获取Cookies")}</li>
                    <li>{_("help.step6", "点击开始下载按钮")}</li>
                    <li>{_("help.step7", "等待下载完成，可在历史记录中查看下载状态或重新下载")}</li>
                </ul>
                
                <h2>🚀 3. {_("help.vpn_recommendation", "科学工具推荐")}</h2>
                <p>{_("help.vpn_intro", "这个工具目前只能是通过邀请码进行注册，邀请链接：")}</p>
                <ul>
                    <li>邀请码:  &nbsp;  &nbsp;  Sr8xvlnt  &nbsp;  &nbsp;  <a href="https://www.bixiny.com/#/register?code=Sr8xvlnt" target="_blank">https://www.bixiny.com/#/register?code=Sr8xvlnt</a></li>
                    <li>邀请码:  &nbsp;  &nbsp;  puQ8ffJb  &nbsp;  &nbsp;  <a href="https://www.bixiny.com/#/register?code=puQ8ffJb" target="_blank">https://www.bixiny.com/#/register?code=puQ8ffJb</a></li>
                    <li>邀请码:  &nbsp;  &nbsp;  cVxin6av  &nbsp;  &nbsp;  <a href="https://www.bixiny.com/#/register?code=cVxin6av" target="_blank">https://www.bixiny.com/#/register?code=cVxin6av</a></li>
                    <li>邀请码:  &nbsp;  &nbsp;  VUExmagq  &nbsp;  &nbsp;  <a href="https://www.bixiny.com/#/register?code=VUExmagq" target="_blank">https://www.bixiny.com/#/register?code=VUExmagq</a></li>
                </ul>
                <p>{_("help.invitation_code_note", "邀请链接后面的code就是邀请码，在注册新用户的时候需要填写。")}</p>
                
                <h2>☕ 4. {_("help.thanks", "感谢使用")}</h2>
                <p>{_("help.coffee_message", "如果觉得此项目有帮助，请赏杯咖啡 ☕")}</p>
                <p>{_("help.support_message", "您的支持是我们持续改进的动力！")}</p>"""
            
            # 只有当图片存在时才添加图片标签
            if coffee_image_base64:
                html_content += f"""
                <p style="margin-bottom:0px ;"><img src="{coffee_image_base64}" alt="Coffee" 
                width="500" height="300" style="display: block; margin: 0 auto;"></p>"""
            else:
                html_content += """
                <p style="text-align: center; color: #ff6b6b;">☕ 咖啡图片加载失败，但我们的感谢之心依然满满！</p>"""
            
            html_content += """
            </body>
            </html>
            """
            
            # 设置HTML内容
            self.ui.txt_content.setHtml(html_content)
            
            # 设置文本浏览器样式
            self.ui.txt_content.setStyleSheet("""
                QTextBrowser {
                    background: transparent;
                    border: 1px solid rgba(0, 212, 255, 0.3);
                    border-radius: 8px;
                    padding: 10px;
                    selection-background-color: rgba(0, 212, 255, 0.3);
                }
                QScrollBar:vertical {
                    background: rgba(255, 255, 255, 0.1);
                    width: 12px;
                    border-radius: 6px;
                    margin: 0px;
                }
                QScrollBar::handle:vertical {
                    background: rgba(0, 212, 255, 0.6);
                    border-radius: 6px;
                    min-height: 20px;
                }
                QScrollBar::handle:vertical:hover {
                    background: rgba(0, 212, 255, 0.8);
                }
            """)
            
            logger_manager.info("项目帮助内容设置完成", "ProjectHelp")
            
        except Exception as e:
            logger_manager.error(f"设置项目帮助内容失败: {e}", "ProjectHelp")

    def setup_connections(self):
        """设置信号连接"""
        try:
            # 连接语言切换信号
            i18n_manager.language_changed.connect(self.on_language_changed)
            
            logger_manager.info("项目帮助信号连接设置完成", "ProjectHelp")
            
        except Exception as e:
            logger_manager.error(f"设置项目帮助信号连接失败: {e}", "ProjectHelp")

    def on_language_changed(self):
        """语言切换时更新内容"""
        try:
            self.setup_content()
            logger_manager.info("项目帮助内容已更新（语言切换）", "ProjectHelp")
        except Exception as e:
            logger_manager.error(f"更新项目帮助内容失败（语言切换）: {e}", "ProjectHelp")

    def closeEvent(self, event):
        """窗口关闭事件"""
        try:
            logger_manager.info("项目帮助窗口正在关闭", "ProjectHelp")
            event.accept()
        except Exception as e:
            logger_manager.error(f"关闭项目帮助窗口时发生错误: {e}", "ProjectHelp")
            event.accept()


def main():
    """测试函数"""
    app = QApplication(sys.argv)
    
    try:
        window = ProjectHelpWindow()
        window.show()
        sys.exit(app.exec())
    except Exception as e:
        print(f"项目帮助窗口测试失败: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()